package com.example.demo.c;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/session")
public class SessionController {
	// 用于测试 SpringBoot 容器是否启动
	// http:localhost:8080/test
	@RequestMapping("/test")
	public String test() {
		return "PING OK";
	}

	// http:localhost:8080/put?key=name&value=liwei
	@RequestMapping("/put")
	public String put(HttpSession session, @RequestParam("key") String key, @RequestParam("value") String value) {
		session.setAttribute(key, value);
		return "PUT OK";
	}

	// http:localhost:8080/get?key=name
	@RequestMapping("/get")
	public String get(HttpSession session, @RequestParam("key") String key) {
		String value = (String) session.getAttribute(key);

		if (value == null || "".equals(value)) {
			return "NO VALUE GET";
		}
		return value;
	}

	@RequestMapping(value = "/first", method = RequestMethod.GET)
	public Map<String, Object> firstResp(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		request.getSession().setAttribute("request Url", request.getRequestURL());
		map.put("request Url", request.getRequestURL());
		return map;
	}

	@RequestMapping(value = "/sessions", method = RequestMethod.GET)
	public Object sessions(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		map.put("sessionId", request.getSession().getId());
		map.put("message", request.getSession().getAttribute("request Url"));
		return map;
	}

}
